<?php

/**
 * This is the model class for table "{{product}}".
 *
 * The followings are the available columns in table '{{product}}':
 * @property integer $id
 * @property integer $category_id
 * @property integer $os_id
 * @property string $name
 * @property string $model
 * @property string $chip
 * @property double $size
 * @property double $weight
 * @property integer $display
 * @property integer $storage
 * @property integer $memory
 * @property integer $sensors
 * @property integer $network
 * @property integer $camera
 * @property string $battery
 * @property string $power
 * @property string $audio
 * @property string $video
 * @property string $extra
 * @property string $details
 * @property string $cover
 * @property integer $is_recommended
 * @property integer $create_time
 * @property integer $update_time
 *
 * The followings are the available model relations:
 * @property Os $os
 * @property Category $category
 * @property Accessory[] $tblAccessories
 * @property Color[] $tblColors
 * @property Io[] $tblIos
 * @property Language[] $tblLanguages
 */
class Product extends CActiveRecord
{
	public $thumbs;
    /**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Product the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{product}}';
	}
    
    /**
     * @return array the behaviors to handle something
     */
    public function behaviors(){
        return array(
        	// Adds time stamp automatically
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
            ),
            // Saves the 'HAS_MANY' and 'MANY_MANY' relational active records along with the main model
            'CSaveRelationsBehavior' => array(
                'class' => 'application.components.CSaveRelationsBehavior'
            ),
        );
    }

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('category_id, name, os_id', 'required'),
			array('category_id, os_id, display, storage, memory, sensors, network, camera, is_recommended', 'numerical', 'integerOnly'=>true),
			array('size, weight', 'numerical'),
			array('name', 'length', 'max'=>128),
			array('model, chip, battery, power', 'length', 'max'=>64),
			array('audio, video, extra, details', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('category_id, os_id, name, model', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'os' => array(self::BELONGS_TO, 'Os', 'os_id'),
			'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
            'display' => array(self::BELONGS_TO, 'Display', 'display'),
            'sensors' => array(self::BELONGS_TO, 'Sensor', 'sensors'),
			'accessories' => array(self::MANY_MANY, 'Accessory', '{{product_accessory_assignment}}(product_id, accessory_id)'),
			'colors' => array(self::MANY_MANY, 'Color', '{{product_color_assignment}}(product_id, color_id)'),
			'ios' => array(self::MANY_MANY, 'Io', '{{product_io_assignment}}(product_id, io_id)'),
			'languages' => array(self::MANY_MANY, 'Language', '{{product_language_assignment}}(product_id, language_id)'),
            'networks' => array(self::MANY_MANY, 'Network', '{{product_network_assignment}}(product_id, network_id)'),
            'pictures' => array(self::HAS_MANY, 'ProductPicture', 'product_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'category_id' => 'Category',
			'os_id' => 'Operation System',
			'name' => 'Name',
			'model' => 'Model',
            'colors' => 'Color',
			'chip' => 'Chip',
			'size' => 'Size',
			'weight' => 'Weight',
			'display' => 'Display',
			'storage' => 'Storage',
			'memory' => 'Memory',
			'sensors' => 'Sensors',
			'networks' => 'Networks',
			'camera' => 'Camera',
			'battery' => 'Battery',
			'power' => 'Power',
			'audio' => 'Audio',
			'video' => 'Video',
            'ios' => 'Input/Output',
            'accessories' => 'Accessories',
            'languages' => 'Languages',
			'extra' => 'Extra',
			'picture' => 'Picture',
			'picture' => 'Cover',
			'details' => 'Details',
			'is_recommended' => 'Recommended?',
            'create_time' => 'Create Time',
			'update_time' => 'Update Time',
		);
	}

	/**
	 * This is invoked before the record is saved.
	 * @return boolean whether the record should be saved.
	 */
	public function beforeSave()
	{
		if (parent::beforeSave()) {

			// Handles the MANY_MANY activeRecord relationship
            $this->setRelationRecords('colors', is_array(@$_POST['Color']) ? $_POST['Color'] : array());
            $this->setRelationRecords('networks', is_array(@$_POST['Network']) ? $_POST['Network'] : array());
            $this->setRelationRecords('accessories', is_array(@$_POST['Accessory']) ? $_POST['Accessory'] : array());
            $this->setRelationRecords('ios', is_array(@$_POST['Io']) ? $_POST['Io'] : array());
            $this->setRelationRecords('languages', is_array(@$_POST['Language']) ? $_POST['Language'] : array());

            return true;

		} else {
			return false;
		}
		
	}

    /**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('category_id',$this->category_id);
		$criteria->compare('os_id',$this->os_id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('model',$this->model,true);

		return new CActiveDataProvider($this, array(
			'pagination'=>array(
				'pageSize'=>Yii::app()->params['pageSize'],
			),
			'sort'=>array(
				'defaultOrder'=>'create_time DESC',
			),
			'criteria'=>$criteria,
		));
	}

	/**
	 * @return string 指定id和size的产品图片
	 */
   	public function getPicture($id, $size)
   	{
   		// 确定图片存储文件夹
   		switch($size) {
   			case 'medium':
    			$folder = 'medium/';
    			break;
    		case 'small':
    			$folder = 'small/';
    			break;
    		default:
    			$folder = '';
    			break;
    	}

    	$picture = ProductPicture::model()->findByPk($id);
   		return CHtml::image(Yii::app()->baseUrl."/uploads/product/".$folder.$picture->name.".".$picture->ext, $this->name, array('rel'=>$id));
   	}

   	/**
   	 * 删除指定目录下的图片
   	 */
   	public function destroyPictures($dir)
	{
		foreach($this->pictures as $picture)
		{
			$pictrue->destroy($dir);
		}
	}

	/**
   	 * 删除该产品的所有图片
   	 */
   	public function destroyAllPictures()
	{
		$dir=Yii::app()->basePath."/../uploads/product/";
		destroyPictures($dir);
		destroyPictures($dir."medium/");
		destroyPictures($dir."small/");
	}

    /**
	 * @return string the URL that shows the detail of the product
	 */
    public function getUrl()
    {
    	return Yii::app()->createUrl('Product/view', array(
    		'id'=>$this->id,
    	));
    }
    
}